package com.example.lenovo_.healthyangel_home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.example.lenovo_.healthyangel.R;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo- on 2016/10/14.
 */
public class HealthysportFragment extends Fragment implements AdapterView.OnItemClickListener{
    private GridView gridView;
    private ViewFlipper flipper;
    private LinearLayout mTipLinearLayout;
    private int[]resId={R.mipmap.saiche,R.mipmap.two_people,R.mipmap.doublepeople,R.mipmap.six_lu,R.mipmap.four_people};
    private float startX;
    private List<Map<String,Object>> dataList;
    private SimpleAdapter adapter;
    private String[] iconName={"球类运动","水上项目","跑步运动","运动步行","单车骑行","形体项目","登山远足","极限运动","其他"};
    private int[] icon={R.mipmap.sport_ball_black,R.mipmap.sport_swim_black,R.mipmap.sport_run_black,R.mipmap.sport_walk_black,R.mipmap.sport_bicycle_black,R.mipmap.sport_formtrain_black,R.mipmap.sport_climb_black,R.mipmap.sport_dangerous_black,R.mipmap.sport_other_black};
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_home_healthysport,null);
        initView(view);
        dataList=new ArrayList<Map<String,Object>>();
        adapter=new SimpleAdapter(this.getContext(),this.getData(),R.layout.home_healthysport_item,new String[]{"image","text"},new int[]{R.id.imageView5,R.id.textView9});
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);
        //动态导入
        for(int i=0;i<resId.length;i++) {
            flipper.addView(getImageview(resId[i]));
        }

//      屏幕下方加入一排小点
//        for (int i=0;i<resId.length;i++){
//            ImageView image=new ImageView(getContext());
//            if(i==0){
//                image.setImageResource(R.mipmap.point_selected);
//            }else {
//                image.setImageResource(R.mipmap.point_normal);
//            }
//            image.setPadding(5,0,5,20);
//            mTipLinearLayout.addView(image);
//        }
//        mTipLinearLayout.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
//        flipper.addView(mTipLinearLayout);

        flipper.setInAnimation(this.getContext(),R.anim.slide_right_in);
        flipper.setOutAnimation(this.getContext(),R.anim.slide_right_out);
        flipper.setFlipInterval(6000);
        flipper.startFlipping();

        flipper.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action=event.getAction();
                switch (action){
                    //手指接触屏幕
                    case MotionEvent.ACTION_DOWN:
                        flipper.setAutoStart(false);
                        startX=(int) event.getX();
                        break;
                    //手指栽屏幕上移动
                    case MotionEvent.ACTION_MOVE:
                        break;
                    //手指离开屏幕
                    case MotionEvent.ACTION_UP: {
                        //手指向右滑动，显示下一张图片
                        if (event.getX() - startX > 100) {
                            flipper.setInAnimation(getContext(), R.anim.slide_right_in);
                            flipper.setOutAnimation(getContext(), R.anim.slide_right_out);
                            flipper.showNext();
                            flipper.setAutoStart(false);
                        }
                        //手指向左滑动，显示前一张图片
                        else if (startX - event.getX() > 100) {
                            flipper.setInAnimation(getContext(), R.anim.slide_left_in);
                            flipper.setOutAnimation(getContext(), R.anim.slide_left_out);
                            flipper.showPrevious();
                            flipper.setAutoStart(false);
                        }
                        else if(startX-event.getX()<10||event.getX()-startX<10){
                            break;
                        }
                    }
                        break;
                }
                //手指不滑动时，继续执行自动向右滚动模式
                flipper.setInAnimation(getContext(),R.anim.slide_right_in);
                flipper.setOutAnimation(getContext(),R.anim.slide_right_out);
                flipper.setFlipInterval(6000);
                flipper.setAutoStart(true);
                return true;
            }
        });
        return view;
    }
    private ImageView getImageview(int resId){
        ImageView image = new ImageView(getContext());
        image.setBackgroundResource(resId);
        return image;
    }
    private void initView(View view) {
        flipper= (ViewFlipper) view.findViewById(R.id.flipper1);
        gridView= (GridView) view.findViewById(R.id.gridView1);
    }


    private List<Map<String,Object>> getData() {
        for (int i=0;i<icon.length;i++){
            Map<String,Object>map=new HashMap<String,Object>();
            map.put("image",icon[i]);
            map.put("text",iconName[i]);
            dataList.add(map);
        }
        return dataList;
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //获取输入流
                    StringBuilder result= (StringBuilder) msg.obj;
                    break;
                case 2:
                    String result2="接到空消息"+msg.what;
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position){
            case 0:
                new Thread(new ThreadGetData0()).start();
                Intent intent=new Intent(this.getContext(),HealthysportLietviewActivity.class);
                startActivity(intent);
                Toast.makeText(getActivity(),"1",Toast.LENGTH_LONG).show();
                break;
            case 1:
                Toast.makeText(getActivity(),"2",Toast.LENGTH_LONG).show();
                break;
            case 2:
                Toast.makeText(getActivity(),"3",Toast.LENGTH_LONG).show();
                break;
            case 3:
                Toast.makeText(getActivity(),"4",Toast.LENGTH_LONG).show();
                break;
            case 4:
                Toast.makeText(getActivity(),"5",Toast.LENGTH_LONG).show();
                break;
            case 5:
                Toast.makeText(getActivity(),"6",Toast.LENGTH_LONG).show();
                break;
            case 6:
                Toast.makeText(getActivity(),"7",Toast.LENGTH_LONG).show();
                break;
            case 7:
                Toast.makeText(getActivity(),"8",Toast.LENGTH_LONG).show();
                break;
            case 8:
                Toast.makeText(getActivity(),"9",Toast.LENGTH_LONG).show();
                break;
        }
//        Toast.makeText(getActivity(),"我是"+iconName[position],Toast.LENGTH_SHORT).show();
    }
    private class ThreadGetData0 implements Runnable{
        @Override
        public void run() {
            HttpURLConnection conn=null;
            try{
                URL url=new URL("http://115.159.149.87:8080/testssm/user/usertest");
                conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                if (conn.getResponseCode()==200){
                    //获取输入流
                    InputStream is=conn.getInputStream();
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
                    StringBuilder stringBuilder=new StringBuilder();
                    String Data;
                    try{
                        while ((Data=bufferedReader.readLine())!=null){
                            stringBuilder.append(Data);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    //封装数据并发送
                    Message message=Message.obtain();
                    message.what=1;
                    message.obj=stringBuilder;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (conn!=null){
                    conn.disconnect();//关闭连接
                }
            }
        }
    }

}
